library("survival")
library("survminer")
## Loading required package: ggplot2
## Loading required package: ggpubr
## 
## Attaching package: 'survminer'
## The following object is masked from 'package:survival':
## 
##     myeloma
library("viridis")
## Loading required package: viridisLite
library("plotly")
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
library("htmlwidgets")
library("GGally")
## Registered S3 method overwritten by 'GGally':
##   method from   
##   +.gg   ggplot2
# ## Multivariable Cox Model:
# res.cox <- coxph(Surv(time, status) ~ age + sex + ph.ecog, data =  lung)
# # summary(res.cox)
# 
# 
# 
# ## Plotting the Survival Model
# # ggsurvplot(survfit(res.cox), color = "#2E9FDF", ggtheme = theme_minimal(), data = lung)
# 
# ##  Creating A New Data Set Keeping age and ph.ecog constant
# sex_df <- with(lung,
#                data.frame(sex = c(1, 2), 
#                           age = rep(mean(age, na.rm = TRUE), 2),
#                           ph.ecog = c(1, 1)
#                )
# )
# 
# 
# # Fitting a basic survival model to this new dataset.
# fit <- survfit(res.cox, newdata = sex_df)
# surv_plot <- ggsurvplot(fit, conf.int = TRUE, legend.labs=c("Sex=Male", "Sex=Female"), ggtheme = theme_minimal(), data = sex_df)
# 
# 
# # class(surv_plot)
# plotly::ggplotly(surv_plot[[1]])






# Improve survival curve model:
# ggsurvplot(fit, conf.int = TRUE, legend.labs=c("Sex=Male", "Sex=Female"), 
#            ggtheme = scale_color_viridis(discrete = TRUE), data = sex_df
#            )

# Fitting model:
surv1 <- survfit(Surv(time,status) ~ sex, data = lung)

# Creating ggplot of survial curves between men and women:
p <- ggsurv(surv1, CI = F)

# Changing color theme & Legend:
p <- p + guides(linetype = "none") +
 scale_color_viridis(name = 'Sex', breaks = c(1,2), labels=c('Male', 'Female'), discrete = TRUE)
## Scale for 'colour' is already present. Adding another scale for 'colour',
## which will replace the existing scale.
# Changing the theme style:
p <- p + theme_minimal()

# Adding a title:
p <- p + ggtitle("Survival Curves of Men and Women With Lung Cancer")


p

# Creating Interactive Plot:
p_i <- plotly::ggplotly(p)


p_i <- p_i %>%
  rangeslider() %>%
  layout(hovermode = "x")


p_i